<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-9-11
 * Time: 上午10:25
 */
namespace Tiny;

class CURL{

  /**
   * curl get请求
   * @param string $url
   * @param array $parameter
   * @return string
   */
  public function get(string $url,array $parameter = []):string {
    $curl = curl_init($url);
    //设置超时
    curl_setopt($curl,CURLOPT_TIMEOUT,30);
    //设置在输出中是否包含header
    curl_setopt($curl,CURLOPT_HEADER,false);
    //设置输出为字符串而不是直接输出
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);

    if (count($parameter) != 0){
      curl_setopt($curl,CURLOPT_URL,$url."?".http_build_query($parameter));
    }
    $res = curl_exec($curl);
    if ($res == false || curl_errno($curl)){
      Logger::getInstance()->fatal("curl get is error,code is ".curl_errno($curl).",msg is ".curl_error($curl));
      return "";
    }
    curl_close($curl);
    return $res;
  }

  /**
   * curl post请求
   * @param string $url
   * @param string $data
   * @param array $headers
   * @return string
   */
  public function post(string $url,string $data,array $headers = []):string {
    $curl = curl_init($url);
    curl_setopt($curl,CURLOPT_TIMEOUT,30);
    curl_setopt($curl,CURLOPT_HEADER,false);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    if (count($headers) != 0){
      curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
    }
    curl_setopt($curl,CURLOPT_POST,1);
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data);

    $res = curl_exec($curl);
    if ($res == false || curl_errno($curl)){
      Logger::getInstance()->fatal("curl post is error,code is ".curl_errno($curl).",msg is ".curl_error($curl));
      return "";
    }
    curl_close($curl);
    return $res;
  }
}